package com.xuerhua.yxt.controller.teacher;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xuerhua.yxt.common.AppUser;
import com.xuerhua.yxt.common.Const;
import com.xuerhua.yxt.common.MenuConst;
import com.xuerhua.yxt.common.RspResult;
import com.xuerhua.yxt.common.enums.Status;
import com.xuerhua.yxt.controller.BaseController;
import com.xuerhua.yxt.model.Grid;
import com.xuerhua.yxt.model.StudentScore;
import com.xuerhua.yxt.page.OrderBy;
import com.xuerhua.yxt.page.Page;
import com.xuerhua.yxt.reqVo.BasePageQueryVO;
import com.xuerhua.yxt.reqVo.BaseQueryVO;
import com.xuerhua.yxt.reqVo.ExamQueryVO;
import com.xuerhua.yxt.reqVo.ExamReqVO;
import com.xuerhua.yxt.reqVo.StudentReqVO;
import com.xuerhua.yxt.service.IClassTeachersService;
import com.xuerhua.yxt.service.IExamService;
import com.xuerhua.yxt.service.IStudentService;
import com.xuerhua.yxt.utils.DateUtil;
import com.xuerhua.yxt.view.ClassForExamRegView;
import com.xuerhua.yxt.view.ExamGroupView;

@Controller
@RequestMapping(Const.TEACHER_ROLE + MenuConst.EXAM_SCORE)
public class ExamScoreController extends BaseController{
	
	private Logger logger = LoggerFactory.getLogger(ExamScoreController.class);
	
	@Autowired
	private IExamService examService;
	@Autowired
	private IClassTeachersService classTeachersService;
	@Autowired
	private IStudentService studentService;

	@RequestMapping(value = {"","/"})
	public String index(Model model) {
		AppUser appUser = getAppUser();
		if(("," + appUser.getTeacher().getPosition() + ",").indexOf(",5,") != -1) {
			model.addAttribute("isAdmin", true);
		}
		return "examScore/index";
	}
	
	@RequestMapping("register")
	public String register() {
		return "examScore/register";
	}
	
	@RequestMapping("examList")
	public String examList(Model model) {
		AppUser appUser = getAppUser();
		if((appUser.getTeacher().getPosition() + ",").indexOf("5,") == -1) {
			return null;
		}
		return "examScore/examList";
	}
	
	@RequestMapping("addExam")
	public String addExam(Model model) {
		AppUser appUser = getAppUser();
		if((appUser.getTeacher().getPosition() + ",").indexOf("5,") == -1) {
			return null;
		}
		model.addAttribute("examKey", null);
		return "examScore/examDetail";
	}
	
	@RequestMapping("examDetail/{examKey}")
	public String examDetail(Model model, @PathVariable String examKey) {
		AppUser appUser = getAppUser();
		if((appUser.getTeacher().getPosition() + ",").indexOf("5,") == -1) {
			return null;
		}
		model.addAttribute("examKey", examKey);
		return "examScore/examDetail";
	}
	
	@RequestMapping("examList/pageQuery")
	@ResponseBody Object pageQuery(BasePageQueryVO vo) {
		try {
			Page<ExamGroupView> page = new Page<ExamGroupView>();
			Grid grid = new Grid();
			List<OrderBy> sorts = new ArrayList<>();
			sorts.add(new OrderBy("examTime", "desc"));
			page.setSorts(sorts);
			page.setParams(vo);
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			List<ExamGroupView> list = examService.selectExamGroupListByPage(page);
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return grid;
		} catch (Exception e) {
			logger.error("---routinePageQuery error={}", e);
		}
		return null;
	}
	
	@RequestMapping("examDetail/query")
	@ResponseBody Object examDetailQuery(String examKey) {
		BaseQueryVO vo = new BaseQueryVO();
		vo.setKey(examKey);
		return examService.selectListByExamKey(vo);
	}
	
	@RequestMapping("exam/addUpdate")
	@ResponseBody Object examAddUpdate(ExamReqVO vo) {
		try {
			vo.setExamTime(DateUtil.strToDate(vo.getExamDate(), DateUtil.DEFAULT_DATE_FORMAT1));
			vo.setRegClosingTime(DateUtil.strToDate(vo.getRegClosingDate(), DateUtil.DEFAULT_DATE_FORMAT1));
			vo.setTermId(getCurrentTerm().getId());
			examService.addAndUpdate(vo);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("---examAddUpdate error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("regExam")
	@ResponseBody Object regExam(ExamQueryVO vo) {
		vo.setTermId(getCurrentTerm().getId());
		return examService.selectRegExamList(vo);
	}
	
	@RequestMapping("examReg/class")
	@ResponseBody Object examRegClass(ExamQueryVO vo) {
		AppUser appUser = getAppUser();
		vo.setSchoolId(appUser.getTeacher().getSchoolId());
		vo.setFinishYear(getCurrentTerm().getFinishYear());
		return getRegClassList(classTeachersService.selectClassForExamReg(vo));
	}
	
	@RequestMapping("student/query")
	@ResponseBody Object studentQuery(StudentReqVO vo) {
		AppUser appUser = getAppUser();
		vo.setSchoolId(appUser.getTeacher().getSchoolId());
		return studentService.selectListByParam(vo);
	}
	
	@RequestMapping("regScoreSubmit")
	@ResponseBody Object regScoreSubmit(List<StudentScore> list) {
		try {
			
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("---regScoreSubmit error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	private static List<ClassForExamRegView> getRegClassList(List<ClassForExamRegView> list) {
		List<ClassForExamRegView> viewList = new ArrayList<>();
		Map<Integer, ClassForExamRegView> map = new HashMap<>();
		for(ClassForExamRegView ct : list) {
			if(!map.containsKey(ct.getGrade())) {
				ClassForExamRegView view = new ClassForExamRegView();
				List<ClassForExamRegView> list2 = new ArrayList<>();
				list2.add(ct);
				view.setGrade(ct.getGrade());
				view.setClassList(list2);
				map.put(ct.getGrade(), view);
				viewList.add(map.get(ct.getGrade()));
				continue;
			}
			((ClassForExamRegView)map.get(ct.getGrade())).getClassList().add(ct);
		}
		map = null;
		return viewList;
	}
}
